<template>
  <div class="main-wrapper">
    <div class="breadcrumb">
      <span class="breadcrumb-item" @click="closeForm('')">标签管理</span>
      <i class="breadcrumb-item-icon el-icon-arrow-right"></i>
      <span class="breadcrumb-item">新增标签</span>
    </div>
    <el-form :model="form" :rules="rules" label-width="120px" class="groupForm" ref="groupForm">
      <div class="top-wrapper">
        <div class="title">基础信息</div>
        <el-row>
          <el-col :span="6">
            <el-form-item label="标签名称:" prop="tagViewName">
              <el-input
                  class="input"
                  v-model="form.tagViewName"
                  placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签ID:" prop="tagName">
              <el-input
                  class="input"
                  v-model="form.tagName"
                  placeholder="请输入"
              >
                <template slot="prepend">Suspect_tag_</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注:" prop="remark">
              <el-input
                  class="input"
                  v-model="form.remark"
                  placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="bot-wrapper">
        <div class="title">标签规则</div>
        <div class="type-tag-wrap">
          <div :class="['tag',{'tag-active':tagIndex === index}]" @click="tagChange(item,index)" v-for="(item,index) in form.categoryList" :key="index"
               :title="item.categoryName || `分类${index+1}`">{{item.categoryName || `分类${index+1}`}}
          </div>
          <div class="tag tag-add" @click="handlePlus"><i class="el-icon-plus"></i></div>
        </div>
        <el-row>
          <el-col :span="6">
            <el-form-item label="分类名称:" prop="categoryName">
              <el-input
                  class="input"
                  v-model="form.categoryList[tagIndex].categoryName"
                  placeholder="请输入"
                  maxlength="50"
                  show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="分类描述:" prop="categoryDesc">
              <el-input
                  class="input"
                  v-model="form.categoryList[tagIndex].categoryDesc"
                  placeholder="请输入"
                  maxlength="100"
                  show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="attribute-wrapper">
          <div class="title-box">
            <span v-if="tagType === 'judicial_case'">案件属性满足</span>
            <span v-if="tagType === 'criminal_suspect'">嫌疑人属性满足</span>
            <span v-if="tagType === 'victim'">受害人属性满足</span>
            <el-button @click="addItem" class="btn-add" type="text" size="small" icon="el-icon-circle-plus-outline">添加</el-button>
          </div>
          <div class="option-parent">
            <div class="option-list-line" v-if="form.categoryList[tagIndex].ruleList.length>1">且</div>
            <div style="flex: 1">
              <div class="option-list" v-for="(item,index) in form.categoryList[tagIndex].ruleList" :key="index">
                <div class="option-box-line" v-if="item.children.length>1">或</div>
                <div style="flex: 1">
                  <div class="option-box clearfix" v-for="(ele,eleIndex) in item.children" :key="eleIndex">
                    <el-select
                        ref="select"
                        clearable
                        v-model="ele.item"
                        class="select1"
                        placeholder="请选择"
                        @change="changeCategoryId($event,ele)"
                    >
                      <el-option :value="op.infoField" :label="op.infoFieldDesc" v-for="(op,index) in selectList" :key="index"></el-option>
                    </el-select>
                    <el-select
                        clearable
                        v-model="ele.calcType"
                        class="select1"
                        @change="ele.itemIsArry = null;ele.rangeValue1 = ''; ele.rangeValue2 = ''"
                        placeholder="请选择"
                        v-if="ele.options && ele.options.length !== 2"
                    >
                      <el-option :value="op.value" :label="op.label" v-for="(op,ox) in dictList" :key="ox"></el-option>
                    </el-select>
                    <el-select
                        clearable
                        v-model="ele.calcType"
                        class="select1"
                        @change="ele.itemIsArry = null;ele.rangeValue1 = ''; ele.rangeValue2 = ''"
                        placeholder="请选择"
                        v-if="ele.options && ele.options.length === 2"
                    >
                      <el-option :value="op.value" :label="op.label" v-for="(op,index) in ele.options" :key="index"></el-option>
                    </el-select>
                    <template v-if="ele.calcType === 'between'">
                      <el-date-picker
                          type="datetime"
                          v-model="ele.rangeValue1"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择时间"
                          style="width:200px;"
                          v-if="['happened_time','birthday','suspect_birthday','victim_birthday'].includes(ele.item)"
                      ></el-date-picker>
                      <el-input
                          class="input topbut"
                          type="number"
                          v-model="ele.rangeValue1"
                          style="width:200px;"
                          v-else
                      ></el-input>
                      <span style="margin: 0 15px">与</span>
                      <el-date-picker
                          type="datetime"
                          v-model="ele.rangeValue2"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择时间"
                          style="width:200px;"
                          v-if="['happened_time','birthday','suspect_birthday','victim_birthday'].includes(ele.item)"
                      ></el-date-picker>
                      <el-input
                          class="input topbut"
                          type="number"
                          v-model="ele.rangeValue2"
                          style="width:200px;"
                          v-else
                      ></el-input>
                      <span style="margin-left: 15px">之间</span>
                    </template>
                    <template v-if="['eq','ne','in','notIn'].includes(ele.calcType)">
                      <el-select
                          clearable
                          collapse-tags
                          :multiple="['in','notIn'].includes(ele.calcType)"
                          v-model="ele.itemIsArry"
                          @change="changeItemIs($event,ele)"
                          class="select1"
                          placeholder="请选择"
                          v-if="ele.options?.length"
                      >
                        <el-option :value="op.value" :label="op.label" v-for="(op,index) in ele.options" :key="index"></el-option>
                      </el-select>
                      <template v-else>

                        <el-date-picker
                            type="date"
                            v-model="ele.itemIsArry"
                            @change="changeItemIs($event,ele)"
                            value-format="yyyy-MM-dd"
                            placeholder="选择日期"
                            style="width:220px;"
                            v-if="['birthday','suspect_birthday','victim_birthday'].includes(ele.item)"
                        >
                        </el-date-picker>
                        <el-date-picker
                            type="datetime"
                            v-model="ele.itemIsArry"
                            @change="changeItemIs($event,ele)"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="选择时间"
                            style="width:220px;"
                            v-else-if="['happened_time'].includes(ele.item)"
                        ></el-date-picker>
                        <el-input
                            class="input"
                            v-model="ele.itemIsArry"
                            @change="changeItemIs($event,ele)"
                            placeholder="请输入"
                            style="width:220px;"
                            v-else
                        ></el-input>
                      </template>
                    </template>
                    <span class="right" v-if="eleIndex === item.children.length - 1">
                      <el-button @click="delItem(index)" class="btn-del" size="small" icon="el-icon-delete" v-if="index > 0 && item.children.length === 1">删除且</el-button>
                      <el-button @click="delEle(item,eleIndex)" class="btn-del" size="small" icon="el-icon-delete" v-if="item.children.length > 1">删除或</el-button>
                      <el-button @click="addEle(item)" class="btn-add" size="small" icon="el-icon-circle-plus-outline">新增</el-button>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="button-wrapper">
          <el-button @click="handleSubmit" :loading="btnLoading" size="small" class="btn plain-btn">创建</el-button>
          <el-button @click="closeForm('')" size="small" class="btn default-btn">取消</el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import {sandbox, addRule} from '@/libs/util'
import groupForm from '@/mixins/groupForm.js'
const categoryList = [
  {
    categoryDesc:'',
    categoryName:'',
    ruleList:[
      {
        calcType:null,
        children:[
          {
            calcType:null,
            id:null,
            item:'',
            itemDesc:'',
            itemIs:'',
            itemIsArry:null,
            logicalOperator:'或',
            orgId:null,
            pid:null,
            rangeValue1:null,
            rangeValue2:null,
            tagId:null,
          },
        ],
        id:null,
        item:'',
        itemDesc:'',
        itemIs:'',
        itemIsArry:null,
        logicalOperator:'且',
        orgId:null,
        pid:null,
        rangeValue1:null,
        rangeValue2:null,
        tagId:null,
      }
    ]
  }
]
export default {
  mixins: [groupForm],
  props: {
    tagType: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      btnLoading: false,
      tagIndex:0,
      form: sandbox({
        tagType:'',
        tagViewName: '',
        tagName: '',
        remark: '',
        categoryList:sandbox(categoryList)
      }),
      rules: {
        tagViewName: [{required: true, message: '必填项', trigger: 'blur'}],
        tagName: [{required: true, message: '必填项', trigger: 'blur'}],
      },
      selectList:[],
      dictList:[
        {
          value:'between',
          label:'区间',
        },
        {
          value:'eq',
          label:'等于',
        },
        {
          value:'ne',
          label:'不等于',
        },
        {
          value:'in',
          label:'包含',
        },
        {
          value:'notIn',
          label:'不包含',
        },
        {
          value:'isNotNull',
          label:'有值',
        },
        {
          value:'isNull',
          label:'没有值',
        }
      ],
    }
  },
  watch:{
    mode(val){
      val && (this.form.tagType = this.tagType)
    },
  },
  methods:{
    handleSubmit () {
      this.$refs.groupForm.validate( valid => {
        if (valid) {
          if(this.validate(this.form)){
            this.$message({
              type: 'warning',
              message: '属性满足有必填项未填写'
            })
            return
          }
          this.btnLoading = true
          ;(this.mode === 'add' ? this.AddRow() : this.UpdateRow())
              .then(() => {
                this.closeForm('reload')
              })
              .finally(() => {
                this.btnLoading = false
              })
        }
      })
    },
    validate(form){
      let result = false
      form.categoryList[this.tagIndex].ruleList.forEach(ele=>{
        ele.children.forEach(item=>{
          if(!item.item){
            result = true
          }

          if(!item.calcType){
            result = true
          } else {
            if(item.calcType === 'between' && (!item.rangeValue1 || !item.rangeValue2)){
              result = true
            }
            if(item.calcType === 'eq' && !item.itemIsArry){
              result = true
            }
            if(item.calcType === 'ne' && !item.itemIsArry){
              result = true
            }
            if(item.calcType === 'in' && !item.itemIsArry?.length){
              result = true
            }
            if(item.calcType === 'notIn' && !item.itemIsArry?.length){
              result = true
            }
          }
        })
      })
      return result
    },
    AddRow(){
      return this.$api.api_urcap_suspectTag_add({
        body: this.form,
        config: {showMsg: true}
      })
    },
    UpdateRow(){
      return this.$api.api_urcap_suspectTag_edit({
        body: this.form,
        config: {showMsg: true}
      })
    },
    async SetData(row){
      this.$api.api_urcap_suspectTag_get({
        param: {id: row.id,},
      }).then(async res => {
        let data = res.data
        data.categoryList.forEach((cate)=>{
          cate.ruleList.forEach((item)=>{
            item.children.forEach(async (ele)=>{
              ele.options = await this.getOptions(ele.item)
              ele.itemIsArry = ele.itemIs
              if(['in','notIn'].includes(ele.calcType)){
                ele.itemIsArry = ele.itemIs.split(',')
              }
            })
          })
        })
        this.$nextTick(()=>{
          Object.assign(this.form, data)
        })
      })
    },
    tagChange(item,index){
      this.tagIndex = index
    },
    handlePlus(){
      this.form.categoryList.push(addRule('ruleItem'))
    },
    // 新增或
    addEle(item){
      item.children.push(addRule('or'))
    },
    // 删除或
    delEle(item,eleIndex){
      item.children.splice(eleIndex,1)
    },
    // 删除且
    delItem(index){
      this.form.categoryList[this.tagIndex].ruleList.splice(index,1)
    },
    // 新增且
    addItem(){
      this.form.categoryList[this.tagIndex].ruleList.push(addRule('also'))
    },

    changeCategoryId(value,ele){
      const selectRow = this.selectList.find(ele => ele.infoField === value)
      ele.options = []
      ele.itemIs = ''
      ele.calcType = ''
      if(selectRow.infoFieldValue){
        ele.options = selectRow.infoFieldValue.replace(/,/g, '、').split('、').map(ele => {
          return {
            value:ele,
            label:ele
          }
        })
        if(ele.options.length === 2){
          ele.options[0].value = 'yes'
          ele.options[1].value = 'no'
        }
      }
      this.$nextTick(()=>{
        ele.itemDesc = this.$refs.select[0].selected.label
      })
    },

    async getOptions(value){
      const selectRow = this.selectList.find(ele => ele.infoField === value)
      let options = []
      if(selectRow.infoFieldValue){
        options = selectRow.infoFieldValue.replace(/,/g, '、').split('、').map(ele => {
          return {
            value:ele,
            label:ele
          }
        })
        if(options.length === 2){
          options[0].value = 'yes'
          options[1].value = 'no'
        }
      }
      return options
    },

    // 格式化itemIs
    changeItemIs(val,ele){
      if(typeof val === 'string'){
        ele.itemIs = val
      } else{
        ele.itemIs = val.join(',')
      }
    },
    // closeForm
    closeForm (isReload= '') {
      this.$emit('back',isReload)
      this.btnLoading = false
      this.$refs.groupForm && this.$refs.groupForm.resetFields()
      this.form = {
        tagType:'',
        tagViewName: '',
        tagName: '',
        remark: '',
        categoryList:sandbox(categoryList)
      }
    },
  },
  created() {
    this.$api.api_urcap_baseInfoAttrDict_queryList({
      body: {
        PageIndex: 1,
        PageSize: 1000,
        infoType:this.tagType,
      },
    }).then(res => {
      this.selectList  =  res.data
    })
  }
}
</script>

<style scoped lang="scss">
.main-wrapper {
  max-width: calc(100vw - 220px);
  height: 100%;
  overflow-y: auto;
  padding: 15px 15px 0 15px;
  box-sizing: border-box;
}

.groupForm {
  height: calc(100% - 240px);

  .title {
    font-weight: 500;
    font-size: 18px;
    color: #333333;
    line-height: 18px;
    border-left: 4px solid #0B085F;
    padding-left: 16px;
    margin-bottom: 20px;
  }
}

.top-wrapper {
  box-sizing: border-box;
  padding: 20px 20px 0 20px;
  background: #FFFFFF;
  border-radius: 8px 8px 8px 8px;
  border: 2px solid #FFFFFF;
}

.bot-wrapper {
  box-sizing: border-box;
  padding: 20px;
  margin-top: 20px;
  height: 100%;
  background: rgba(255, 255, 255, 0.502);
  border-radius: 8px 8px 8px 8px;
  border: 2px solid #FFFFFF;
  overflow-y: auto;

  .type-tag-wrap {
    display: flex;
    flex-wrap: wrap;

    .tag {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 160px;
      height: 46px;
      padding: 0 10px;
      background: #FFFFFF;
      border-radius: 8px;
      border: 1px solid #DCE1E4;
      margin-right: 25px;
      margin-bottom: 25px;
      color: #D4D4D4;
      font-size: 14px;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .tag-active{
      border: 1px solid #0B085F;
      color: #0B085F;
    }

    .tag-add {
      font-size: 30px;
    }
  }
}

.button-wrapper {
  margin-top: 30px;
  padding-top: 15px;
  border-top: 1px solid #DCE1E4;

  .btn {
    width: 120px;
    height: 46px;
    border-radius: 8px;
  }
}
</style>